package 网络编程.udpEchoServerCilent;
import java.io.IOException;
import java.net.*;
import java.util.*;

/**
 * 实现回显服务器-客户端
 * 协议 : UDP
 */
public class UdpEchoCilent {
    // 客户端
    private DatagramSocket socket = null;

    public UdpEchoCilent() throws SocketException {
        socket = new DatagramSocket();  // 客户端一般不指定端口号
    }

    // 发送请求, 并接收响应
    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        while (true) {
            // 1. 构造请求, 发送请求
            System.out.print("> ");
            String request = in.next();
            // 请求 数据报
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName("127.0.0.1"), 6666);
            socket.send(requestPacket);
            // 2. 接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4069], 4069);
            socket.receive(responsePacket);
            // 3. 解析响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("request -> %s  |  response -> %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoCilent cilent = new UdpEchoCilent();
        cilent.start();
    }
}
